﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Threading;
using System.Globalization;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 22/06/2011
    /// Modified by Viet LV (01/10/2011)
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class LegalDocumentController : Controller
    {
        SDTDataContext eDataContext = new SDTDataContext();

        public LegalDocumentController()
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        }
        //
        // GET: /LegalDocument/
		[RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("legaldocument.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("legaldocument.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("legaldocument.CatID", "CatID", 0));
                    string strPub = UserState.getUserStateFromRequest("legaldocument.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string keyword = UserState.getUserStateFromRequest("legaldocument.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("legaldocument.pageSize", "PageSize", 20).ToString());

                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    var docs = eDataContext.LegalDocuments
                        .Where(d => (catID > 0 ? d.CatID == catID : true))
                        .Where(c => currentPub.HasValue ? c.ActiveYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(d => (string.IsNullOrEmpty(keyword) ? true : ((d.LegalNumber.ToLower().Contains(keyword.ToLower().Trim()))||
                            (d.Singer.ToLower().Contains(keyword.ToLower().Trim()))||
                            (d.LegalDocumentNote.ToLower().Contains(keyword.ToLower().Trim())))))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = catID > 0 ? new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, catID) : new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    var listLagelCategoryDefault = Utils.StringToDictionary(Settings.Default.LegalCategoryDefault,",");
                    var listLagelPublisherDefault = Utils.StringToDictionary(Settings.Default.LegalPublisherDefault, ",");
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new LegalDocumentViewModels
                    {
                        Documents = docs,
                        Categories = categories,
                        CurrentCat = catID,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        LegCategoryDefault = listLagelCategoryDefault,
                        LegPublisherDefault = listLagelPublisherDefault,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /LegalDocument/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    LegalDocument formDoc = eDataContext.LegalDocuments.Where(f => f.ID == id).FirstOrDefault();
                    List<Document> listDoc = (from doc in eDataContext.Documents
                                              join docIn in eDataContext.DocumentsInLegalDocuments on doc.ID equals docIn.DocumentID into docInForm
                                              from docu in docInForm.DefaultIfEmpty()
                                              where doc.ActiveYN == true && docu.LegalDocumentID == id
                                              select doc).ToList();

                    List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();

                    TreeNodeCollection categories = formDoc.CatID.HasValue && formDoc.CatID.Value > 0 ?
                                                    new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, formDoc.CatID.Value) :
                                                    new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    var listLagelPublisherDefault = Utils.StringToDictionary(Settings.Default.LegalPublisherDefault,",");
                    var listLagelCategoryDefault = Utils.StringToDictionary(Settings.Default.LegalCategoryDefault,",");
                    var currentPublisher = "";
                    foreach (var item in listLagelPublisherDefault)
                    {
                        if (Convert.ToInt32(item.Key) == formDoc.Publisher)
                        {     currentPublisher = item.Value.ToString();
                        break;}
                    }
                    var currentCategory = "";
                    foreach (var item in listLagelCategoryDefault)
                    {
                        if (Convert.ToInt32(item.Key) == formDoc.CatID)
                        {
                            currentCategory = item.Value.ToString();
                            break;
                        }
                    }
                var seconPublisher="";
                foreach(var item in listLagelPublisherDefault)
                    {
                        if(formDoc.SeconPublisher!= null && formDoc.SeconPublisher == Convert.ToInt32(item.Key))
                        {
                            seconPublisher = item.Value.ToString();
                            break;
                        }
                    }

                    return View(new LegalDocumentInputModels
                    {
                        Categories = categories,
                        Document = formDoc,
                        listDocu = listDoc,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.MagazineFileRootPathUrl,
                        CurrentCategory = currentCategory,
                        CurrentPublic = currentPublisher,
                        SeconPublic = seconPublisher
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /LegalDocument/Create
        public ActionResult Create()
        {
            try
            {
                var listLegCategoryDefault = Utils.StringToDictionary(Settings.Default.LegalCategoryDefault, ",");
                var listLegPublisherDefault = Utils.StringToDictionary(Settings.Default.LegalPublisherDefault, ",");
                    List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new LegalDocumentInputModels
                    {
                        Categories = categories,
                        LegCategoryDefault = listLegCategoryDefault,
                        LegPublisherDefault = listLegPublisherDefault
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /LegalDocument/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(LegalDocumentInputModels m)
        {
            try
            {
                    UpdateModel(m.Document);
                  //  m.Document.CatID = short.Parse(Request["CatID"]);
                    m.Document.AddBy = UserManager.GetUserId();
                    m.Document.AddDate = DateTime.Now;

                    eDataContext.LegalDocuments.InsertOnSubmit(m.Document);
                    eDataContext.SubmitChanges();

                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                        {
                            var index = inputTagName.Substring(inputTagName.IndexOf("fileInput") + 9);
                            Document doc = new Document();
                            doc.AddDate = DateTime.Now;
                            doc.ActiveYN = true;
                            doc.AddBy = UserManager.GetUserId();
                            doc.AddDate = DateTime.Now;
                            doc.Description = Request["description" + index];
                            doc.Name = Request["fileName" + index];
                            doc.Path = file.FileName;
                            doc.nDownload = 0;
                            doc.ModifyBy = UserManager.GetUserId();
                            doc.ModifyDate = DateTime.Now;
                            string filePath = string.Empty;
                            eDataContext.Documents.InsertOnSubmit(doc);
                            eDataContext.SubmitChanges();
                            //Insert table mapping
                            DocumentsInLegalDocument docInForm = new DocumentsInLegalDocument();
                            docInForm.DocumentID = doc.ID;
                            docInForm.LegalDocumentID = m.Document.ID;

                            eDataContext.DocumentsInLegalDocuments.InsertOnSubmit(docInForm);
                            eDataContext.SubmitChanges();
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID, file.FileName);
                            file.SaveAs(filePath);

                        }
                    }
                    #endregion

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /LegalDocument/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                var listLagelCategoryDefault = Utils.StringToDictionary(Settings.Default.LegalCategoryDefault,",");
                var listLagelPublisherDefault = Utils.StringToDictionary(Settings.Default.LegalPublisherDefault,",");
                
                    LegalDocument formDoc = eDataContext.LegalDocuments.Where(f => f.ID == id).FirstOrDefault();
                    List<Document> listDoc = (from doc in eDataContext.Documents
                                              join docIn in eDataContext.DocumentsInLegalDocuments on doc.ID equals docIn.DocumentID into docInForm
                                              from docu in docInForm.DefaultIfEmpty()
                                              where doc.ActiveYN == true && docu.LegalDocumentID == id
                                              select doc).ToList();

                    List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();

                    TreeNodeCollection categories = formDoc.CatID.HasValue && formDoc.CatID.Value > 0 ?
                                                    new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, formDoc.CatID.Value) :
                                                    new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new LegalDocumentInputModels
                    {
                        Categories = categories,
                        Document = formDoc,
                        listDocu = listDoc,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.MagazineFileRootPathUrl,
                        LegCategoryDefault = listLagelCategoryDefault,
                        LegPublisherDefault = listLagelPublisherDefault
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /LegalDocument/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, LegalDocumentInputModels m)
        {
            try
            {
                    m.Document = eDataContext.LegalDocuments.Where(d => d.ID == id).FirstOrDefault();
                    UpdateModel(m.Document);
                    UpdateModel(m.Document);
                    m.Document.CatID = short.Parse(Request["CatID"]);
                    m.Document.ModifyBy = UserManager.GetUserId();
                    m.Document.ModifyDate = DateTime.Now;

                    eDataContext.SubmitChanges();

                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                        {
                            var index = inputTagName.Substring(inputTagName.IndexOf("fileInput") + 9);
                            Document doc = new Document();
                            doc.AddDate = DateTime.Now;
                            doc.ActiveYN = true;
                            doc.AddBy = UserManager.GetUserId();
                            doc.AddDate = DateTime.Now;
                            doc.Description = Request["description" + index];
                            doc.Name = Request["fileName" + index];
                            doc.Path = file.FileName;
                            doc.nDownload = 0;
                            doc.ModifyBy = UserManager.GetUserId();
                            doc.ModifyDate = DateTime.Now;
                            string filePath = string.Empty;
                            eDataContext.Documents.InsertOnSubmit(doc);
                            eDataContext.SubmitChanges();
                            //Insert table mapping
                            DocumentsInLegalDocument docInForm = new DocumentsInLegalDocument();
                            docInForm.DocumentID = doc.ID;
                            docInForm.LegalDocumentID = m.Document.ID;

                            eDataContext.DocumentsInLegalDocuments.InsertOnSubmit(docInForm);
                            eDataContext.SubmitChanges();
                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID);
                            }
                            filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.MagazineFileRootPath + doc.ID, file.FileName);
                            file.SaveAs(filePath);

                        }
                    }
                    #endregion

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    int nItem = eDataContext.DocumentsInLegalDocuments.Where(d => d.LegalDocumentID == id).Count();
                    if (nItem > 0)
                        throw new Exception("Bạn phải xoá tệp tin trước khi xoá biểu mẫu này.");

                    LegalDocument formDoc = eDataContext.LegalDocuments.Where(f => f.ID == id).FirstOrDefault();

                    return View(formDoc);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    LegalDocument formDoc = eDataContext.LegalDocuments.Where(f => f.ID == id).FirstOrDefault();
                    if (formDoc != null)
                    {
                        eDataContext.LegalDocuments.DeleteOnSubmit(formDoc);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
